<template>
  <div class="question-show">
    <question-card :question="question" />

    <!-- 留言区 -->
    <comment-list ref="commentList" :qid="question.id" :fetcher="fetchComments" />
    <mu-sub-header>发表留言</mu-sub-header>
    <mu-text-field
      v-model="comment.input"
      full-width
      placeholder="请在这里填写留言，要注意言行哦！"
      multi-line
      :rows="1"
      :rows-max="6"
    />
    <div class="submit-box">
      <mu-checkbox v-model="comment.requestCheck" label="请求重审此题"></mu-checkbox>
      <mu-button color="success" @click="createComment()">发表留言</mu-button>
    </div>

    <!-- 编辑区 -->
    <div v-if="isAuthor">
      <mu-sub-header>题目编辑</mu-sub-header>
      <mu-button class="edit-button" color="orange" @click="editQuestion()">编辑此题</mu-button>
      <mu-button class="edit-button" color="error" @click="handleRemoveQuestion()">删除此题</mu-button>
    </div>
  </div>
</template>

<script>
import api from '@/api'
import { mapGetters } from 'vuex'
import { textToColor } from '@/util/colors'
import { parseTime } from '@/util'
import CommentList from './CommentList'
import QuestionCard from '@/components/QuestionCard'

export default {
  name: 'QuestionShow',
  components: {
    QuestionCard,
    CommentList
  },
  props: {
    id: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      question: {
        id: 0,
        type_id: 0,
        author_id: 0,
        style: 0,
        image: null,
        text: '',
        options: [],
        answer: '',
        status: 0,
        pass_count: 0,
        fail_count: 0,
        is_exported: 0,
        create_at: 0,
        update_at: 0,
        author: {
          id: 0,
          username: '',
          realname: '',
          role: 0,
          is_superadmin: false,
          is_active: true,
          register_at: 0,
          last_login_at: 0
        },
        image_url: null
      },
      comment: {
        inpuut: '',
        requestCheck: false
      }
    }
  },
  computed: {
    ...mapGetters({
      currentUser: 'currentUser',
      getTypeTextById: 'getTypeTextById'
    }),
    typeText() {
      return this.getTypeTextById(this.question.type_id)
    },
    color() {
      return textToColor(this.typeText)
    },
    options() {
      const result = []
      for (let i = 0; i < this.question.options.length; i++) {
        const text = this.question.options[i]
        const mark = String.fromCharCode(65 + i)
        result.push({ text, mark })
      }
      return result
    },
    isAuthor() {
      const currentUserId = this.currentUser ? this.currentUser.id : 0
      const questionAuthorId = this.question.author_id
      return currentUserId === questionAuthorId
    }
  },
  watch: {
    id() {
      this.showQuestion()
    }
  },
  created() {
    this.showQuestion()
  },
  methods: {
    async showQuestion() {
      this.loading = true
      try {
        this.question = await api.getQuestion(this.id)
      } catch (err) {
        this.$apiCatch(err)
      }
      this.loading = false
    },
    fetchComments(page) {
      const id = this.question.id
      if (id === 0) {
        return Promise.resolve(null)
      } else {
        return api.fetchQuestionCommentMessages(id, page)
      }
    },
    toDatetimeString(time) {
      return parseTime(time, '{y}-{m}-{d} {h}:{i}:{s}')
    },
    buildRatioText(question) {
      const pass = question.pass_count
      const fail = question.fail_count
      const total = pass + fail
      return `${pass} / ${total}`
    },
    // 发表留言
    async createComment() {
      try {
        await api.createQuestionCommentMessage(this.question.id, this.comment.input, { request_check: this.comment.requestCheck })
        this.$toast.success('留言成功' + (this.comment.requestCheck ? '，已通知审题组' : ''))
        this.$refs.commentList.refresh()
      } catch (err) {
        this.$apiCatch(err)
      }
    },
    // 编辑题目
    async editQuestion() {
      this.$router.push({
        name: 'question-edit',
        params: {
          id: this.question.id
        }
      })
    },
    // 用户点击了删除
    handleRemoveQuestion() {
      this.$confirm('删除题目无法恢复，确定继续？', '提示', {
        type: 'warning'
      }).then(({ result }) => {
        if (result) {
          this.$confirm('真的真的不能恢复哦，确定吗？', '提示', {
            type: 'warning'
          }).then(({ result }) => {
            if (result) {
              this.removeQuestion()
            } else {
              this.$toast.message('已取消')
            }
          })
        } else {
          this.$toast.message('已取消')
        }
      })
    },
    // 删除题目
    async removeQuestion() {
      try {
        await api.removeQuestion(this.question.id)
        this.$toast.success('删除成功')
        this.$router.go(-1)
      } catch (err) {
        this.$apiCatch(err)
      }
    }
  }
}
</script>

<style scoped>
.question-show {
  padding: 20px;
}
.edit-button {
  margin: 4px 8px 4px 0;
}
.submit-box {
  display: flex;
  flex-flow: column;
  align-items: flex-end;
  padding: 0 16px;
}

.is-phone .question-show {
  padding: 12px;
}
</style>
